/**
 * @description: 这是Eirudy创建的类~
 * @author: Eirudy
 * @hope: 憧憬成为java大师
 **/

package org.eirudy.shareimage.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.eirudy.shareimage.annotation.AuthCheck;
import org.eirudy.shareimage.api.aliyunai.AliYunAiApi;
import org.eirudy.shareimage.api.aliyunai.model.CreateOutPaintingTaskRequest;
import org.eirudy.shareimage.api.aliyunai.model.CreateOutPaintingTaskResponse;
import org.eirudy.shareimage.api.aliyunai.model.GetOutPaintingTaskResponse;
import org.eirudy.shareimage.api.imagesearch.ImageSearchApiFacade;
import org.eirudy.shareimage.api.imagesearch.model.ImageSearchResult;
import org.eirudy.shareimage.common.BaseResponse;
import org.eirudy.shareimage.common.DeleteRequest;
import org.eirudy.shareimage.common.PageRequest;
import org.eirudy.shareimage.common.ResultUtils;
import org.eirudy.shareimage.constant.UserConstant;
import org.eirudy.shareimage.exception.BusinessException;
import org.eirudy.shareimage.exception.ErrorCode;
import org.eirudy.shareimage.exception.ThrowUtils;
import org.eirudy.shareimage.manager.CosManager;
import org.eirudy.shareimage.manager.auth.SpaceUserAuthManager;
import org.eirudy.shareimage.manager.auth.StpKit;
import org.eirudy.shareimage.manager.auth.annotation.SaSpaceCheckPermission;
import org.eirudy.shareimage.manager.auth.model.SpaceUserPermissionConstant;
import org.eirudy.shareimage.model.dto.picture.*;
import org.eirudy.shareimage.model.entity.Picture;
import org.eirudy.shareimage.model.entity.Space;
import org.eirudy.shareimage.model.entity.User;
import org.eirudy.shareimage.model.enums.PictureReviewStatusEnum;
import org.eirudy.shareimage.service.impl.PictureServiceImpl;
import org.eirudy.shareimage.service.impl.SpaceServiceImpl;
import org.eirudy.shareimage.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.eirudy.shareimage.model.vo.PictureVO;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private CosManager cosManager;

    @Resource
    private PictureServiceImpl pictureService;

    @Resource
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();
    @Autowired
    private SpaceServiceImpl spaceServiceImpl;
    @Autowired
    private AliYunAiApi aliYunAiApi;
    @Autowired
    private SpaceUserAuthManager spaceUserAuthManager;


    @PostMapping("/upload")
    @SaSpaceCheckPermission(value= SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile file,
                                                 PictureUploadRequest pictureUploadRequest, HttpServletRequest httpServletRequest){

        User user = userService.getLoginUser(httpServletRequest);

        PictureVO picture = pictureService.uploadPicture(file,pictureUploadRequest,user);

        return ResultUtils.success(picture);

    }

    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value= SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadRequest pictureUploadRequest, HttpServletRequest httpServletRequest){

        User user = userService.getLoginUser(httpServletRequest);
        String url = pictureUploadRequest.getUrl();
        PictureVO picture = pictureService.uploadPicture(url,pictureUploadRequest,user);

        return ResultUtils.success(picture);

    }

    /**
     * 图片删除
     * @param deleteRequest
     * @param request
     * @return
     */
    @DeleteMapping("/delete")
    @SaSpaceCheckPermission(value= SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request){
        if(deleteRequest == null || deleteRequest.getId() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //接下来校验删除者的身份，如果是管理员或者图片的创建者，就可以删除图片了
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        pictureService.deletePicture(id,user);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片
     * @param pictureUploadRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUploadRequest,HttpServletRequest request) {
        if (pictureUploadRequest == null || pictureUploadRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginuser = userService.getLoginUser(request);
        Picture oldPicture = pictureService.getById(pictureUploadRequest.getId());
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureUploadRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureUploadRequest.getTags()));

        //校验一下picture
        pictureService.validPicture(picture);

        //填充审核参数
        pictureService.fillReviewParams(picture,loginuser);

        boolean result = pictureService.updateById(picture);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(true);

    }


    /**
     * 管理员特供，根据id获取图片
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(id);

        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        return ResultUtils.success(picture);
    }

    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVoById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(id);

        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }


        //空间权限校验
        Long spaceId = picture.getSpaceId();
        Space space = null;
        if (spaceId != null) {
            boolean b = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!b, ErrorCode.NO_AUTH_ERROR);
            space = spaceServiceImpl.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);

        }
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, userService.getLoginUser(request));
        PictureVO pictureVO = pictureService.getPictureVO(picture,request);
        pictureVO.setPermissionList(permissionList);

        return ResultUtils.success(pictureVO);
    }

    /**
     *  获得图片信息分页列表，管理员使用的
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();

        Page<Picture> picturePage = pictureService.page(new Page<>(current,size),
                pictureService.getQueryWrapper(pictureQueryRequest));

        return ResultUtils.success(picturePage);
    }

    /**
     * 获得图片信息vo 所有人可用
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVoByPage(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();



        //空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null) {
            // 空间图库
            //将请求的审核状态强制设置为pass状态，普通用户只能看见pass后的。
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        }else{
            boolean b = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!b, ErrorCode.NO_AUTH_ERROR);
//            User loginuser = userService.getLoginUser(request);
//            Space space = spaceServiceImpl.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
//            if(!loginuser.getId().equals(space.getUserId())){
//                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"无空间权限");
//            }
        }

        Page<Picture> picturePage = pictureService.page(new Page<>(current,size),
                pictureService.getQueryWrapper(pictureQueryRequest));

        return ResultUtils.success(pictureService.getPictureVOPage(picturePage,request));
    }

    /**
     * 获得图片信息vo 所有人可用, 有缓存，这个函数可以考虑去封装一下 todo,有时间去重构一下
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @Deprecated
    @PostMapping("/list/page/cache")
    public BaseResponse<Page<PictureVO>> listPictureVoByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();

        //将请求的审核状态强制设置为pass状态，普通用户只能看见pass后的。
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        // 先查一下缓存，缓存中没有再查询数据库,这里用一下多级缓存
        //构建缓存的key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String redisKey = String.format("shareImage:listPictureVOByPage:%s",hashKey);

        //先查一下本地缓存
        String cacheValue = LOCAL_CACHE.getIfPresent(hashKey);
        if (cacheValue != null) {
            // 缓存命中，直接返回
            Page<PictureVO> pageCache = JSONUtil.toBean(cacheValue,Page.class);
            return ResultUtils.success(pageCache);
        }

        // 如果本地缓存没有命中，操作redis
        ValueOperations<String,String> opsForValue = stringRedisTemplate.opsForValue();
        cacheValue = opsForValue.get(redisKey);
        if(cacheValue != null){
            // 缓存命中，保存在本地缓存中，并直接返回
            LOCAL_CACHE.put(hashKey,cacheValue);
            Page<PictureVO> pageCache = JSONUtil.toBean(cacheValue,Page.class);
            return ResultUtils.success(pageCache);
        }

        //如果都没有命中，查数据库,并且把结果保存到本地缓存和redis缓存中
        Page<Picture> picturePage = pictureService.page(new Page<>(current,size),
                pictureService.getQueryWrapper(pictureQueryRequest));

        //获得voPage,将其转化为json字符串，并且保存到cache中
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage,request);
        String voString = JSONUtil.toJsonStr(pictureVOPage);
        LOCAL_CACHE.put(hashKey,voString);

        //设置缓存过期时间 随机5-10分钟，防止缓存雪崩(同一时间缓存批量过期导致连接全部跑数据库了）
        int cacheExpireTime = 300+ RandomUtil.randomInt(0,300);
        opsForValue.set(redisKey,voString,cacheExpireTime, TimeUnit.SECONDS);
        return ResultUtils.success(pictureVOPage);
    }

    @PostMapping("/edit")
    @SaSpaceCheckPermission(value= SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if(pictureEditRequest == null || pictureEditRequest.getId() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //仅管理员或者本人可以修改
        User user = userService.getLoginUser(request);

        pictureService.editPicture(pictureEditRequest,user);

        return ResultUtils.success(true);

    }

    /**
     *  审核图片
     * @param pictureReviewRequest
     * @param request
     * @return
     * @throws BusinessException
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> ReviewPicture(PictureReviewRequest pictureReviewRequest,HttpServletRequest request){
        ThrowUtils.throwIf(pictureReviewRequest == null,ErrorCode.PARAMS_ERROR,"参数为空");
        User loginuser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest,loginuser);
        return ResultUtils.success(true);
    }


    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest, HttpServletRequest request){
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null,ErrorCode.PARAMS_ERROR);

        User loginuser = userService.getLoginUser(request);

        Integer result = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest,loginuser);

        return ResultUtils.success(result);
    }


    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);

        Long picId = searchPictureByPictureRequest.getPictureId();

        ThrowUtils.throwIf(ObjectUtil.isNull(picId), ErrorCode.PARAMS_ERROR);

        Picture picture = pictureService.getById(picId);
        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "请求图片不存在");
        }

        List<ImageSearchResult> imageSearchResults = ImageSearchApiFacade.searchImage(picture.getUrl());

        return ResultUtils.success(imageSearchResults);
    }

    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value= SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }

    /**
     *  批量对标签和tag进行更新
     * @param pictureEditByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value= SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 创建Ai扩图任务
     */
    @PostMapping("/out_painting/create_task")
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
                                                                                    HttpServletRequest request) {
        ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);

        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);

        return ResultUtils.success(response);

    }

    /**
     *  获得AI扩图任务的结果
     * @param taskId
     * @return
     */
    @GetMapping("/out_painting/get_task")
    @SaSpaceCheckPermission(value= SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTaskStatus(String taskId){
        ThrowUtils.throwIf(taskId == null || StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);

        GetOutPaintingTaskResponse response = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(response);
    }
}
